<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-4-12
 * Time: 下午4:11
 */

/**
 * 对上传的APK包进行解析，获取 APK内部版本号等数据
 * @param string $apk_file //需要解析的APK文件，绝对路径
 * @return false 表示解析失败
 */
function apk_resolve($apk_file){
    $command = dirname(PUBLICPATH)."/tools/aapt.exe d badging ".$apk_file;
    exec ($command,$out,$return);
    //有时会返回一个数组，如果返回的为数组，将将其转换为 字符串
    if(is_array($out)){
        $str  = '';
        foreach($out as $val){
            $str .= $val."\n";
        }
        $out = $str;
    }
    $res = array();
    if($return == 0 ) {
        $par = "/package: name='([^']*)'/iUes";
        preg_match($par,$out,$arr);
        if(isset($arr[1])){
            $res['app_package_name'] = $arr[1];
        }
        $par = "/versionCode='([^']*)'/iUes";
        preg_match($par,$out,$arr);
        if(isset($arr[1])){
            $res['app_inner_version_code'] = $arr[1];
        }
        $par = "/versionName='([^']*)'/iUes";
        preg_match($par,$out,$arr);
        if(isset($arr[1])){
            $res['app_inner_version_name'] = $arr[1];
        }
        $par = "/label='([^']*)'/iUes";
        preg_match($par,$out,$arr);
        if(isset($arr[1])){
            $res['app_label_name'] = $arr[1];
        }
        $par = "/icon='([^']*)'/iUes";
        preg_match($par,$out,$arr);
        if(isset($arr[1])){
            $res['app_icon'] = $arr[1];
        }
        $par = "/sdkVersion:'([^']*)'/iUes";
        preg_match($par,$out,$arr);
        if(isset($arr[1])){
            $res['app_min_version'] = $arr[1];
        }
        $par = "/uses-permission:'([^']*)'[\r\n]?/i";
        preg_match_all($par,$out,$arr);
        if(isset($arr[1])){
            $res['app_permissions'] = $arr[1];
            foreach($res['app_permissions'] as $k=>&$v){
                $v = substr($v,strrpos($v,'.')+1);
            }
        }
    }
    return $res;
}

/**
 *  版本号比较
 *  @param $v1 新版本号
 *  @param $v2 旧版本号
 *  return boolean
 */
function compareVersion($v1,$v2){
    if(empty($v1)){
        return false;
    }
    $l1  = explode('.',$v1);
    $l2  = explode('.',$v2);
    $len = count($l1) > count($l2) ? count($l1): count($l2);
    for ($i = 0; $i < $len; $i++){
        $n1 = isset($l1[$i]) ? $l1[$i] : 0 ;
        $n2 = isset($l2[$i]) ? $l2[$i] : 0 ;
        if ($n1 > $n2){
            return true;//需要更新
        }else if ($n1 < $n2){
            return false;//不需要更新
        }
    }
    return false;
}
